const jwt = require('jsonwebtoken');
const { util, query, deleteMailCache, addMailCache } = require('../util/util');
const schedule = require("node-schedule");


let allServices = {
    /**
     * @function /calendar/getProcess
     * @type GET
     * @param {time} 可选, 有则搜索特定时间的所有行程
     * @description { 获取行程列表 }
     * @returns { result } 
     */
    async getProcess(time) {
        let res
        if (time == 0) {
            const _sql = `select * from calendar where is_deleted = 0 order by id asc`
            res = await query(_sql)
                /**
                 * 此处可优化, 应该用数据结构的方式而不应该遍历
                 */
            const data = []
            res.map((item) => {
                // isAdd: 是否有相同的日期
                let isAdd = false
                data.map((ev) => {
                        if (item.time === ev.time) {
                            ev.event.push({
                                id: item.id,
                                process: item.process,
                                notify: item.notify
                            })
                            isAdd = true
                        }
                    })
                    // 如果没有相同日期
                if (isAdd === false) {
                    data.push({
                        time: item.time,
                        event: [
                            { id: item.id, process: item.process, notify: item.notify }
                        ]
                    })
                }
            })
            return util.msgFormatter(data, `获取成功`, 200)
        } else {
            const _sql = `select * from calendar where is_deleted = 0 and time = ? order by id asc`
            res = await query(_sql, [time])
            return util.msgFormatter(res, `获取成功`, 200)
        }
    },

    /**
     * @function /calendar/addProcess
     * @type POST
     * @param { time } 时间
     * @param { process } 行程内容
     * @param { notify } 是否提醒
     * @description { 新增行程 }
     * @returns { result } 
     */
    async addProcess(process, time, notify) {
        const year = parseInt(time.substring(0, 4))
        const month = parseInt(time.substring(5, 7))
        const day = parseInt(time.substring(time.length - 2, time.length))
        const today = new Date()
        if (day <= today.getDate()) return util.msgFormatter([], `仅支持设置隔日及以后的行程`, 401)

        const sql = `INSERT INTO calendar(process, notify, time, is_deleted) VALUES (?, ?, ?, ?)`
        const res = await query(sql, [process, notify, time, 0])

        // 设置定时发邮件
        if (notify == 1) {
            addMailCache(res.insertId, time, process)
        }

        let date = new Date(year, month - 1, day + 3, 0, 0, 0);
        await schedule.scheduleJob(date, () => {
            // 在行程过去3天后自动将该行程从数据库中进行逻辑删除
            allServices.deleteProcess(res.insertId);
        });

        return util.msgFormatter([], `新增行程成功`, 200)
    },




    /**
     * @function /calendar/deleteProcess
     * @type POST
     * @param { processId } 行程id
     * @description { 删除行程 }
     * @returns { result } 
     */
    async deleteProcess(processId) {
        const sql = `UPDATE calendar SET is_deleted= ? WHERE id = ?`
        const res = await query(sql, [1, processId])

        // 停止定时任务，并将定时任务从缓存中删除
        deleteMailCache(processId)
        return util.msgFormatter([], `行程删除成功`, 200)
    },



    /**
     * @function /calendar/changeNotifyProcess
     * @type POST
     * @param { notify } 行程提醒状态
     * @param { processId } 行程id
     * @description { 修改行程为提醒/不提醒状态 }
     * @returns { result } 
     */
    async changeNotifyProcess(processId, notify) {
        const sql = `UPDATE calendar SET notify= ? WHERE id = ?`
        await query(sql, [notify, processId])

        // 此处应有更好的办法, 获取对应processId的time
        const _sql = `select * from calendar where id = ? order by id asc`
        const res = await query(_sql, [processId])

        // 不管是否修改为提醒或不提醒，都需要先将对应的缓存先删除
        deleteMailCache(processId)

        // 根据notify的状态处理邮件缓存
        if (notify == 1) {
            addMailCache(processId, res[0].time, res[0].process)
        }

        return util.msgFormatter([], `行程提醒状态已更改`, 200)
    },
}

module.exports = allServices;